﻿#include "downloadmq.h"
#include <QDebug>

DownloadMQ* DownloadMQ::instance = nullptr;
QMutex DownloadMQ::mutex;
DownloadMQ::DownloadMQ(QObject *parent) : QObject(parent)
{
    
    redis = new QtRedis("chunsource.top",2022);
    if(redis->openConnection())
    {
        if(redis->auth("161100Me"))
        {
            //qDebug()<<"成功连接redis ";
        }
    }
    
    
}


DownloadMQ::~DownloadMQ()
{
    foreach (auto item, map_downloadStore) {
        qDebug()<<"释放 "<<item.data;
        delete[] item.data;
    }
}

DownloadMQ *DownloadMQ::Instance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new DownloadMQ();
        }
        locker.unlock();
    }
    return instance;
}

void DownloadMQ::download(QString qurl)
{
    QJsonObject obj;
    obj["url"] = qurl;
}

void DownloadMQ::download(QJsonObject obj)
{
    QString qurl = obj["url"].toString();  //url
    
    QMutexLocker locker(&dmutex);
    if(set_downloadMQ.find(qurl) != set_downloadMQ.end())
    {
        //找打了，解锁返回
        locker.unlock();
        return;
    }
    
    //没找到，插入，解锁，继续
    set_downloadMQ.insert(qurl);
    locker.unlock();
    DownloadManager* manager = new DownloadManager("./library");  
    
        connect(manager,&DownloadManager::downloadFinsh,[=](QString name){
            redis->set(qurl.toUtf8().toBase64(),name);
            delete manager;
        });
        
    if(obj["path"].toString() == "")
    {
        obj["path"] = QUrl(qurl).path();
    }
    manager->append(obj);  //添加到队列
    
}

bool DownloadMQ::getFile(QString url, CFile &file)
{
    QMutexLocker locker(&dmutex);
    auto it = map_downloadStore.find(url);
    if( it != map_downloadStore.end())
    {
        file.data = it->data;
        file.size = it->size;
        file.len = it->len;
        locker.unlock();
        return true;
    }
    return false;
}

bool DownloadMQ::getFileDatabase(QString url)
{
    QString value = redis->get(url.toUtf8().toBase64());
    qDebug()<<"value "<<value;
    if(value == "" || value.toLower() == "null")
    {
        return false;
    }
    return true;
}
